package cn.edu.ncut.cs.springboot.mybatisplusemployee.service.impl;

import cn.edu.ncut.cs.springboot.mybatisplusemployee.entity.User;
import cn.edu.ncut.cs.springboot.mybatisplusemployee.mapper.UserMapper;
import cn.edu.ncut.cs.springboot.mybatisplusemployee.service.IUserService;
import cn.edu.ncut.cs.springboot.mybatisplusemployee.VO.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserVO> findAll() {
        List<User> users = userMapper.selectList(null);
        return users.stream().map(user -> convertToUserVO(user)).collect(Collectors.toList());
    }

    @Override
    public Optional<User> getByUsername(@NonNull String username) {
        List<User> users = userMapper.getUserByUsername(username);
        return users.stream()
                .findFirst(); // 使用findFirst来获取第一个元素，如果没有元素则返回空的Optional
    }

    @Override
    public boolean create(UserVO userVO) {
        User user = convertToUser(userVO);
        // 假设UserMapper中已经包含了密码加密的逻辑
        int result = userMapper.insert(user);
        return result > 0;
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    private User convertToUser(UserVO userVO) {
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        // 如果UserMapper中没有处理密码加密，则在这里进行加密
        // user.setPassword(passwordEncoder.encode(user.getPassword()));
        return user;
    }

    private UserVO convertToUserVO(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setTimestamp(Instant.now().toEpochMilli());
        return userVO;
    }
}